﻿//
// Copyright (C) Ashish Kaila 2011
//

using System;
using System.Windows.Input;

namespace Flipbook.Commands
{
    public class DispatchCommand : ICommand 
    {
        /// <summary>
        /// Occurs when changes occur that affect whether or not the command should execute.
        /// </summary>
        public event EventHandler CanExecuteChanged;

        /// <summary>
        /// Initializes a new instance of the <see cref="DispatchCommand"/> class.
        /// </summary>
        /// <param name="executeAction">The execute action.</param>
        public DispatchCommand(Action<object> executeAction)
            : this (executeAction, null)
        {            
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DispatchCommand"/> class.
        /// </summary>
        /// <param name="executeAction">The execute action.</param>
        /// <param name="canExecutePredicate">The can execute predicate.</param>
        public DispatchCommand(Action<object> executeAction, Predicate<object> canExecutePredicate)
        {
            _executeAction = executeAction;
            _canExecutePredicate = canExecutePredicate;
        }

        /// <summary>
        /// Defines the method to be called when the command is invoked.
        /// </summary>
        /// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
        public void Execute(object parameter)
        {
            if ((_canExecutePredicate == null) || (_canExecutePredicate(parameter)))
            {
                if (_executeAction != null)
                {
                    _executeAction(parameter);
                }
            }
        }

        /// <summary>
        /// Defines the method that determines whether the command can execute in its current state.
        /// </summary>
        /// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
        /// <returns>
        /// true if this command can be executed; otherwise, false.
        /// </returns>
        public bool CanExecute(object parameter)
        {
            return _canExecutePredicate == null || _canExecutePredicate(parameter);
        }

        // Private members
        private readonly Action<object> _executeAction;
        private readonly Predicate<object> _canExecutePredicate;
    }
}
